package com.ruhua.java.service;

import com.ruhua.java.dao.Image;
import com.ruhua.java.exception.TrowException;
import com.ruhua.java.repository.ImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;


@Service
public class UploadService {
    @Autowired
    ImageRepository imageRepository;

    @Value("${static.local.upload-file-path}")
    private String filePath;

    private static final List<String> CONTENT_TYPE = Arrays.asList("image/gif", "image/jpeg","image/png");


    public String uploadImage(MultipartFile file) {
        String contentType = file.getContentType();
        if (!CONTENT_TYPE.contains(contentType)) {
            throw new TrowException("图片类型错误");
        }

        String oldName = file.getOriginalFilename();
        String suffixName = oldName.substring(oldName.lastIndexOf("."));
        String fileName = UUID.randomUUID() + suffixName;
        try {
            BufferedImage read = ImageIO.read(file.getInputStream());
            if (read == null) {
                throw new TrowException("检验文件失败");
            }
            file.transferTo(new File(this.filePath + "/imgs/" +  fileName));
            Image imgItem=Image.builder()
                    .url(fileName)
                    .categoryId(0)
                    .isVisible(1)
                    .build();
            imageRepository.save(imgItem);
        } catch (Exception e) {
            System.out.println("图片上传：" + e.getMessage());
            throw new TrowException("保存路径错误");
            }
        return fileName;
    }
}